package com.yuanyefu.jdbc;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by 339814 on 2017/9/18.
 */
public class JdbcTemplateBookDao extends JdbcDaoSupport implements BookDao{
    @Override
    public List<Book> queryAll() {
        return getJdbcTemplate().query("select * from Book",new BookRowMapper());
    }

    @Override
    public List<Book> queryByAuthor(String author) {
        return getJdbcTemplate().query("select * from Book where author=?",new Object[]{author},new BookRowMapper());
    }

    @Override
    public void create(Book book) {
        getJdbcTemplate().update("INSERT INTO Book (id,name,author) VALUES (?,?,?)",new Object[]{book.getId(),book.getName(),book.getAuthor()});
    }

    @Override
    public void update(Book book) {
        getJdbcTemplate().update("UPDATE Book SET name =? , author=? WHERE id=?",new Object[]{book.getName(),book.getAuthor(),book.getId()});
    }

    @Override
    public void delete(String id) {
        getJdbcTemplate().update("DELETE from Book WHERE id=?",new Object[]{id});
    }

     class BookRowMapper implements RowMapper<Book> {

        @Override
        public Book mapRow(ResultSet resultSet, int rowNum) throws SQLException {
            Book book = new Book();
            book.setId(resultSet.getString("id"));
            book.setName(resultSet.getString("name"));
            book.setAuthor(resultSet.getString("author"));
            return book;
        }
    }

}
